﻿using System;
using System.Threading;
using System.Windows.Forms;

namespace HYCodeBase.WinForm.BackGroundProgressBar
{
	public class ProgressBarManger
	{
		private Thread UseBackGroundThread
		{
			get
			{
				Thread useBackGroundThread;
				lock (this)
				{
					useBackGroundThread = this.m_useBackGroundThread;
				}
				return useBackGroundThread;
			}
			set
			{
				lock (this)
				{
					this.m_useBackGroundThread = value;
				}
			}
		}

		public bool IfManualAbsort
		{
			get
			{
				bool bIfManualAbsort;
				lock (this)
				{
					bIfManualAbsort = this.m_bIfManualAbsort;
				}
				return bIfManualAbsort;
			}
			private set
			{
				lock (this)
				{
					this.m_bIfManualAbsort = value;
				}
			}
		}

		public ProgressBarManger(BackWorkDelegate inputWork)
		{
			this.m_inputWork = inputWork;
			this.m_uesWork = new BackWorkDelegate(this.UseWork);
		}

		public void ShowFormAndDoWork(IWin32Window parentForm = null)
		{
			this.m_useForm = new ProgressBarForm(this);
			this.m_uesWork.BeginInvoke(null, null);
			if (parentForm == null)
			{
				this.m_useForm.ShowDialog();
				return;
			}
			this.m_useForm.ShowDialog(parentForm);
		}

		private void UseWork()
		{
			try
			{
				this.UseBackGroundThread = Thread.CurrentThread;
				this.m_inputWork();
			}
			catch (Exception)
			{
				ProgressBarManger obj = this;
				lock (obj)
				{
					if (!this.IfManualAbsort)
					{
						this.CloseForm();
					}
				}
			}
			finally
			{
				ProgressBarManger obj = this;
				lock (obj)
				{
					if (!this.IfManualAbsort)
					{
						this.CloseForm();
					}
				}
			}
		}

		public void AbsortThread()
		{
			if (this.UseBackGroundThread != null && this.UseBackGroundThread.IsAlive)
			{
				lock (this)
				{
					try
					{
						this.UseBackGroundThread.Abort();
						this.IfManualAbsort = true;
					}
					catch (Exception)
					{
					}
				}
			}
		}

		private void CloseForm()
		{
			if (this.m_useForm != null && !this.m_useForm.IsDisposed)
			{
				this.m_useForm.IfCanClose = true;
				this.m_useForm.Close();
			}
		}

		private bool m_bIfManualAbsort;

		private ProgressBarForm m_useForm;

		private BackWorkDelegate m_inputWork;

		private BackWorkDelegate m_uesWork;

		private Thread m_useBackGroundThread;
	}
}
